
/*********** CLIENT TCP **************/

#include<stdio.h>
#include<unistd.h>
#include<fcntl.h>
#include<sys/stat.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<netdb.h>
#include<stdlib.h>
#include<string.h>

#define SERVEUR "127.0.0.1"
#define PORTS "2058"
#define TAILLE_BUF 256

int main(int argc, char *argv[])
{
  int sockfd, new_fd, rv, sin_size, n, f, cpt;
  struct addrinfo hints, *servinfo, *p;
  struct sockaddrtheir_adr;
  char buf[TAILLE_BUF];
  
  memset(&hints, 0, sizeof(hints));
  hints.ai_family = AF_UNSPEC;
  hints.ai_socktype = SOCK_STREAM;
  rv = getaddrinfo(SERVEUR, PORTS, &hints, &servinfo);
    
  if(rv!= 0)
  { 
    fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
    return 1;
  }

  // Création socket et attachement
  for(p = servinfo; p != NULL; p = p->ai_next)
  {
    if((sockfd= socket(p->ai_family, p->ai_socktype,p->ai_protocol)) == -1)
    {
      perror("client: socket");
      continue;
    }

    if(connect(sockfd, p->ai_addr, p->ai_addrlen) == -1)
    {
      close(sockfd);
      perror("client: connect");
      continue;
    }
    
    break;
  }

  if(p == NULL)
  {
    perror("server: failed to bind\n");
    exit(2);
  }

  printf("Connexion au serveur reussie\n");

  bzero(buf,256);

  f=open("./testClient.txt", O_RDONLY);
  
  if(f==-1)
  {
    perror("client: erreur ouverture fichier de lecture.\n");
    exit(3);
  }

  printf("Fichier ouvert en lecture\n");
  printf("Demarrage envoie fichier au serveur\n");

  while((cpt=read(f, buf, TAILLE_BUF))>0)
  {
    printf("Lecture de %d octets dans fichier ouvert\n", cpt);
    n = send(sockfd, buf, cpt, 0);

    if(n < 0)
    {
	perror("ERROR writing to socket");
    }
    printf("%d octets envoyes au serveur: %s\n",n,buf);
  }
  
  if(cpt==-1)
  {
    perror("client: erreur lecture fichier.\n");
    exit(3);
  }
  
  printf("Fichier envoye avec succes.\n");
  close(f);
  
  freeaddrinfo(servinfo); // Libère structure

  close(sockfd);
  exit(0);
}
